<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:用户应用权限组
 * @LastEditors: liuhongbin
 */

namespace app\common\model\addonAuth;


use app\common\model\addon\Addons;
use app\common\model\BaseModel;

class UserAddonGroup extends BaseModel
{
    protected $autoWriteTimestamp = false;
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'user_addon_group';

    /**
     * 字段类型或者格式转换
     * @var array
     */
    protected $type = [
        'addon_group_ids' => 'json',
    ];

    /**
     * 保存用户应用组ID通过应用组列表
     * @param $uid
     * @param array $addon_groups
     */
    public function saveAddonGroupIdsByAddonGroups($uid, $addon_groups = [])
    {
        $user_addon_group = $this->where(['uid' => $uid])->findOrEmpty();
        $addon_group_ids = [];
        foreach ($addon_groups as $key => $value) {
            $addon_group_ids[] = $value['id'];
        }
        $user_addon_group->uid = $uid;
        $user_addon_group->addon_group_ids = $addon_group_ids;
        $user_addon_group->save();
    }


    /**
     * 获取用户的应用组列表作为权限选择使用
     * @param $uid
     * @return array|\think\Collection
     */
    public function getUserAddonGroupForSelect($uid)
    {
        $addonGroup = new AddonGroup();
        $row = $this->where(['uid' => $uid])->find();
        if (!$row) {
            return [];
        }
        $row_ids = $row->toArray()['addon_group_ids'];
        $data = $addonGroup->whereIn('id', $row_ids)->select();
        if (!$data) {
            return [];
        }
        foreach ($data as $key => $value) {
            $data[$key]['explain'] = $addonGroup->getExplainByAddons($value['addons']);
        }
        return $data;
    }
}